<template>
  <div class="basic-info">
    <el-card class="box-card">
      <div slot="header">
        <span>基本信息</span>
      </div>
      <el-form :model="formData" ref="form" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入库单号" prop="code">
              <el-input v-model="formData.orderNo" disabled placeholder="系统自动生成">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库主题" prop="subject">
              <el-input v-model="formData.inboundTheme" placeholder="请输入">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入库类型" prop="type">
              <el-input v-model="formData.inboundType" disabled placeholder="普通入库">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库日期" prop="date">
              <el-date-picker v-model="formData.inboundDate" type="date" placeholder="请选择日期" style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入库申请人">
              <el-input v-model="formData.inboundApplicants" disabled placeholder="admin">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在部门">
              <el-input v-model="formData.department" disabled placeholder="生产部门">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库名称" prop="warehouse">
              <el-select v-model="formData.warehouse" placeholder="请选择" style="width: 100%">
                <el-option v-for="item in warehouseOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库人员">
              <el-input v-model="formData.inboundPersonnel" placeholder="请输入">
                <el-button slot="append" icon="el-icon-search" @click="handleSearch23"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库管理员">
              <el-input v-model="formData.warehouseAdministrator" placeholder="请输入">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在部门">
              <el-input v-model="formData.department2" placeholder="请输入">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注">
          <el-input type="textarea" v-model="formData.remark" :rows="3" placeholder="请输入备注">
          </el-input>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="box-cardh2">
      <div slot="header">
        <span>入库明细</span>
      </div>
      <div class="operation-buttons">
        <el-button type="success" @click="dialogVisible = true">添加</el-button>
        <el-button type="info" @click="handleBatchRemove">移除</el-button>
      </div>

      <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column prop="index" label="序号" width="60">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template slot-scope="scope">
            <el-button type="text" style="color: #67C23A" @click="handleRemove(scope.$index)">移除</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="code" label="备件编码" width="120" align="center">
        </el-table-column>
        <el-table-column prop="name" label="备件名称" width="120" align="center">
        </el-table-column>
        <el-table-column prop="specification" label="规格型号" width="120" align="center">
        </el-table-column>
        <el-table-column prop="type" label="备件类型" width="120" align="center">
        </el-table-column>
        <el-table-column prop="brand" label="品牌" width="100" align="center">
        </el-table-column>
        <el-table-column prop="unit" label="单位" width="80" align="center">
        </el-table-column>
        <el-table-column prop="list[0].openingInventory" label="当前库存" width="100" align="center">
        </el-table-column>
        <el-table-column label="入库数量" width="130" align="center">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.amount" :min="0" :max="scope.row.list[0].openingInventory" size="mini"
              controls-position="right" @change="calculateTotal">
            </el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="location" label="存放位置" width="150" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.location" size="mini" placeholder="请输入存放位置">
            </el-input>
          </template>
        </el-table-column>
        <el-table-column prop="remark2" label="备注" width="150" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.remark2" size="mini" placeholder="请输入备注">
            </el-input>
          </template>
        </el-table-column>
      </el-table>

      <div class="total-amount">
        入库总数量：<span class="amount">{{ totalAmount }}</span>
      </div>
    </el-card>

    <!--关联文件-->
    <div>
      <el-card class="box-card3aa">
        <div slot="header" class="clearfix">
          <span>关联文件</span>
        </div>
        <el-button-group style="margin-bottom: 20px;">
          <el-upload ref="upload2" action="http://localhost:9289/maintenance/upload2" :on-success="handleUploadSuccess2"
            :file-list="fileList" :auto-upload="true" :show-file-list="false" :before-upload="beforeUpload">
            <el-button>上传文档</el-button>
          </el-upload>
          <el-button @click="removeSelectedRows2" style="margin-left: 112px;
    margin-top: -36px;">移除</el-button>
        </el-button-group>
        <el-table :data="documents" style="width: 100%;" border @selection-change="handleSelectionChange2">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column type="index" label="序号" width="50"></el-table-column>
          <el-table-column prop="name" label="文件名"></el-table-column>
          <el-table-column prop="uploadDate" label="上传时间"></el-table-column>
          <el-table-column prop="uploader" label="上传者"></el-table-column>
          <el-table-column prop="size" label="文档大小"></el-table-column>
          <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <el-button type="text" @click="removeRow3(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <div style="height: 120px;">
      <el-footer class="footer">
        <el-button @click="handleCancelguan" style="margin-top: 20px; margin-left: -140px;">关闭</el-button>
        <el-button type="primary" @click="handleConfirmkai" style="margin-top: 20px; margin-left: 20px;">确认</el-button>
      </el-footer>
    </div>
    <!--选择入库明细-->
    <el-dialog title="选择备件" :visible.sync="dialogVisible" width="63%" :before-close="handleClose">

      <!-- 搜索区域 -->
      <div class="search-container">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-input v-model="searchForm.keyword" placeholder="请输入备件编号/名称/规格型号" clearable>
            </el-input>
          </el-col>
          <el-col :span="6">
            <el-select v-model="searchForm.type" placeholder="请选择备件类型" clearable style="width: 100%">
              <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select v-model="searchForm.location" placeholder="请选择备件存放位置" clearable style="width: 100%">
              <el-option v-for="item in locationOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-col>
        </el-row>

        <el-row :gutter="10" style="margin-top: 15px">
          <el-col :span="6">
            <el-input v-model="searchForm.brand1" placeholder="请输入备件品牌" clearable>
            </el-input>
          </el-col>
          <el-col :span="6">
            <el-input v-model="searchForm.brand2" placeholder="请输入备件品牌" clearable>
            </el-input>
          </el-col>
          <el-col :span="4" :offset="8" style="text-align: right">
            <el-button type="primary" size="small" @click="handleSearch">查询</el-button>
            <el-button type="success" size="small" @click="handleConsult">咨询</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 表格区域 -->
      <el-table :data="tableData2" style="width: 100%; margin-top: 20px" size="mini"
        @selection-change="handleSelectionChangerr">
        <el-table-column type="selection" width="55" align="center">
        </el-table-column>
        <el-table-column label="序号" type="index" width="60" align="center">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="code" label="备件编码" width="120" align="center">
        </el-table-column>
        <el-table-column prop="name" label="备件名称" width="120" align="center">
        </el-table-column>
        <el-table-column prop="specification" label="规格型号" width="120" align="center">
        </el-table-column>
        <el-table-column prop="type" label="备件类型" width="120" align="center">
        </el-table-column>
        <el-table-column prop="brand" label="品牌" width="120" align="center">
        </el-table-column>
        <el-table-column prop="unit" label="单位" width="80" align="center">
        </el-table-column>
        <el-table-column prop="list[0].openingInventory" label="当前库存" width="100" align="center">
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]" :page-size="pageSize" layout="prev, pager, next, sizes, total" :total="total">
        </el-pagination>
      </div>

      <!-- 底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </div>
    </el-dialog>

    <!--选择人员弹窗-->
    <el-dialog :visible.sync="centerDialogVisible" title="选择人员" width="500px">
      <el-input v-model="search" placeholder="请输入搜索" prefix-icon="el-icon-search"
        style="margin-bottom: 10px;"></el-input>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-tree :data="treeData" :props="defaultProps" node-key="id" highlight-current default-expand-all
            @node-click="handleNodeClick">
          </el-tree>
        </el-col>
        <el-col :span="12">
          <el-card shadow="never" class="box-card5">
            <div slot="header" class="clearfix">
              <span>已选对象 {{ selectedNodes.length }}</span>
              <el-button type="text" @click="clearSelection" style="float: right; padding: 3px 0;">清空</el-button>
            </div>
            <el-tag v-for="(node, index) in selectedNodes" :key="index" closable @close="removeNode(node)">
              {{ node.label }}
            </el-tag>
          </el-card>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSelection">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { SelectLedger2, SelectLedger, InsertNormalWarehousing } from "@/api/eastjet-maintenance/tai/tai";
export default {
  name: 'BasicInfo',
  data() {
    return {
      //选择人员数据
      centerDialogVisible: false,
      selectedNodes: [],
      TestSearch: "",
      search: "",
      treeData: [
        {
          label: 'XXXX科技有限公司',
          children: [
            {
              label: '项目部',
              children: [
                { label: '王虎' },
                { label: '于红' },
              ],
            },
            {
              label: '设计部',
              children: [
                { label: '丁坤' },
                { label: '吴婷' },
              ],
            },
            {
              label: '财务部',
              children: [
                { label: '马书奇' },
                { label: '曹爽' },
              ],
            },
            {
              label: '人事部',
              children: [
                { label: '王志强' },
              ],
            },
          ],
        },
      ],
      //选择入库明细
      dialogVisible: false,
      // 搜索表单
      searchForm: {
        keyword: '',
        type: '',
        location: '',
        brand1: '',
        brand2: ''
      },
      // 备件类型选项
      typeOptions: [
        { value: '1', label: '机械备件' },
        { value: '2', label: '电气备件' }
      ],
      // 存放位置选项
      locationOptions: [
        { value: '1', label: '仓库A' },
        { value: '2', label: '仓库B' }
      ],
      // 表格数据
      tableData2: [],
      // 分页相关
      currentPage: 1,
      pageSize: 10,
      total: 45,
      // 选中的数据
      selectedItems: [],
      //关联文件上传
      documents: [],
      fileList: [],
      multipleSelection: [],
      formData: {
        code: '系统自动生成',
        inboundTheme: '',
        inboundType: '普通入库',
        inboundDate: '',
        inboundApplicants: this.$store.state.user.name,
        department: '生产部门',
        warehouse: '',
        inboundPersonnel: '',
        warehouseAdministrator: '',
        department2: '',
        remark: '',
        documents: [],
        tableData: []
      },

      warehouseOptions: [
        { value: 'warehouse1', label: '仓库1' },
        { value: 'warehouse2', label: '仓库2' },
        { value: 'warehouse3', label: '仓库3' }
      ],
      tableData: [],
      selectedRows: [],
      totalAmount: 0
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      SelectLedger().then(res => {
        this.tableData2 = res.data.data.list
        this.tableData2.forEach(item => {
          for (let i = 1; i < item.list.length; i++) {
            item.list[0].openingTotals += item.list[i].openingTotals
            item.list[0].openingInventory += item.list[i].openingInventory
          }
        })
        this.total = res.data.data.total
        console.log("设备数据", res.data.data)
      })
    },
    handleCancelguan() {
      this.$router.go(-1)
    },
    //提交数据
    handleConfirmkai() {
      this.formData.tableData = this.tableData
      this.fetchData.documents = this.documents
      InsertNormalWarehousing(this.formData).then(res => {
        if (parseInt(res.data.code) == 520) {
          this.$notify({
            title: '入库成功',
            message: '这是一条成功的提示消息',
            type: 'success'
          });
          this.$router.go(-1)
        }
      })
    },
    //选择人员
    confirmSelection() {
      this.formData.inboundPersonnel = this.selectedNodes[0].label
      this.formData.department2 = this.selectedNodes[0].fu

      this.centerDialogVisible = false;
    },
    handleNodeClick(data) {
      let fu = ''
      if (!this.selectedNodes.includes(data) && data.children == null) {
        this.selectedNodes = []
        this.treeData.forEach(item => {
          item.children.forEach(item2 => {
            item2.children.forEach(r => {
              if (r.label === data.label) {
                fu = item2.label
              }
            })
          })
        })
        this.selectedNodes.push({ ...data, fu: fu });
      }
    },
    removeNode(node) {
      this.selectedNodes = this.selectedNodes.filter(n => n !== node);
    },
    clearSelection() {
      this.selectedNodes = [];
    },    // 搜索
    handleSearch() {
      // 实现搜索逻辑
      console.log('搜索条件：', this.searchForm)
    },
    // 咨询
    handleConsult() {
      // 实现咨询逻辑
      console.log('咨询')
    },
    // 选择项变化
    handleSelectionChangerr(val) {
      this.selectedItems = val
    },
    // 每页条数改变
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    // 获取数据
    fetchData() {
      // 实现获取数据的逻辑
    },
    // 取消
    handleCancel() {
      this.dialogVisible = false
      this.$emit('cancel')
    },
    // 确认
    handleConfirm() {
      this.tableData = []
      this.$emit('confirm', this.selectedItems)
      this.selectedItems.forEach(item => {
        this.tableData.push({ ...item, amount: 0, location: '', remark2: '' })
      })
      this.dialogVisible = false
    },
    // 关闭前的回调
    handleClose(done) {
      done()
    },
    //关联文件上传
    beforeUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isLt10M) {
        this.$message.error("上传文件大小不能超过 10MB!");
      }
      return isLt10M;
    },
    removeRow3(index) {
      this.documents.splice(index, 1);
    },
    removeSelectedRows2() {
      this.documents = this.documents.filter(
        (item) => !this.multipleSelection.includes(item)
      );
    },
    handleSelectionChange2(val) {
      this.multipleSelection = val;
    },
    //文件上传成功时候
    handleUploadSuccess2(response, file, fileList) {
      this.documents.push({
        name: file.name,
        url: file.url,
        uploadDate: new Date().toLocaleDateString('zh').replaceAll('/', '-'),
        uploader: this.$store.state.user.name,
        size: file.size + " KB",
      });
      console.log("数据2", this.documents);
    },
    handleSearch23() {
      // 实现人员搜索功能
      this.centerDialogVisible = true
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          console.log('表单数据:', this.formData)
        } else {
          return false
        }
      })
    },    // 移除单行
    handleRemove(index) {
      this.$confirm('确认移除该行数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableData.splice(index, 1)
        this.updateIndexes()
        this.calculateTotal()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => { })
    },

    // 批量移除
    handleBatchRemove() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择要移除的行')
        return
      }
      this.$confirm(`确认移除选中的 ${this.selectedRows.length} 条数据?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const indexes = this.selectedRows.map(row => this.tableData.indexOf(row))
        indexes.sort((a, b) => b - a)
        indexes.forEach(index => {
          this.tableData.splice(index, 1)
        })
        this.updateIndexes()
        this.calculateTotal()
        this.$message({
          type: 'success',
          message: '批量删除成功!'
        })
      }).catch(() => { })
    },

    // 选择行变化
    handleSelectionChange(val) {
      this.selectedRows = val
    },

    // 更新序号
    updateIndexes() {
      this.tableData.forEach((item, index) => {
        item.index = index + 1
      })
    },

    // 计算总数量
    calculateTotal() {
      this.totalAmount = this.tableData.reduce((sum, row) => {
        return sum + (Number(row.amount) || 0)
      }, 0)
    }

  }
}
</script>

<style scoped>
.search-container {
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  margin-top: 20px;
  text-align: right;
}

.fixed-footer-page {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

.footer {
  text-align: center;
  background-color: #eeeded;
  position: fixed;
  bottom: 0;
  z-index: 1;
  width: 100%;
}

.basic-info {
  padding: 20px;
}

.box-card {
  width: 1210px;
  height: 480px;
  margin-left: 14px;
}

.box-cardh2 {
  width: 1210px;
  margin-top: 20px;
  margin-left: 14px;
}

.box-card3aa {
  width: 1210px;
  margin-left: 10px;
  margin-top: 20px;
}

.el-select {
  width: 100%;
}

.warehouse-detail {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
}

.operation-buttons {
  margin-bottom: 20px;
}

.total-amount {
  margin-top: 20px;
  text-align: right;
  font-size: 14px;
  padding-right: 20px;
}

.amount {
  color: #F56C6C;
  font-weight: bold;
}

.el-input-number--mini {
  width: 100%;
}

.el-table .cell {
  padding-left: 10px;
  padding-right: 10px;
}

.el-input--mini {
  font-size: 12px;
}
</style>
